<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <style>
        #app{
            padding: 20px;
        }

        .el-dialog {
            width: 400px;
        }

        .el-form {
            text-align: center;
        }

        .el-form-item {
            margin-bottom: 15px;
            display: flex;
            justify-content: center;
            align-items: center; /* 让标签和输入框在垂直方向上居中对齐 */
        }

        .el-form-item label {
            width: 80px;
            text-align: right;
            margin-right: -100px;
        }

        .el-input,
        .el-date-picker {
            width: 200px;
        }

        .el-switch {
            margin-left: 0;
        }
        .search-form {
            justify-content: flex-start;
            display: flex;
            flex-wrap: wrap;
        }

        .search-form .el-form-item {
            margin-right: 15px;
        }
    </style>
</head>
<body>
<div id="app">
    <!--标题-->
    <h1 style="text-align: center">用户管理</h1>
    <!--查询条件-->
    <el-form :inline="true" :model="searchUser" class="demo-form-inline search-form">
        <el-form-item  style="margin-right: 15px;">
            <el-input v-model="searchUser.username" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item style="margin-right: 15px;">
            <el-input v-model="searchUser.companyName" placeholder="所属企业名称"></el-input>
        </el-form-item>
        <el-form-item >
            <el-select v-model="searchUser.isActive" placeholder="请选择状态">
                <el-option label="请选择状态" value=" "></el-option>
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="findByPage">查询</el-button>
        </el-form-item>
    </el-form>
    <!--新增按钮-->
    <el-row>
        <el-button type="primary" @click="adduser()">新增用户</el-button>
    </el-row>

    <!--表格数据-->
    <template>
        <el-table
                ref="multipleTable"
                :data="users"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column
                    align="center"
                    prop="userId"
                    label="用户id">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="username"
                    label="账号">
            </el-table-column>
<!--            <el-table-column-->
<!--                    align="center"-->
<!--                    prop="passwordHash"-->
<!--                    label="密码">-->
<!--            </el-table-column>-->
            <el-table-column
                    align="center"
                    prop="fullName"
                    label="用户全名">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="contactPhone"
                    label="联系电话">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="companyName"
                    label="所属企业名称">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="createdAt"
                    label="创建时间">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="状态">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.isActive"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="1"
                            inactive-value="0"
                            @change="changeStatus(scope.row)">
                        </el-switch>
                    </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="lastLoginTime"
                    label="最后登入时间">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="failedLoginAttempts"
                    label="连续登入失败次数">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="操作">
                <template slot-scope="scope">
                    <el-row>
                        <el-tooltip content="编辑" placement="top">
                            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>
                        </el-tooltip>
                        <el-tooltip content="重置密码" placement="top">
                            <el-button type="warning" @click="resetPwd(scope.row)" icon="el-icon-refresh"  circle></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button type="danger" @click="deluser(scope.row.userId)" icon="el-icon-delete" circle></el-button>
                        </el-tooltip>
                    </el-row>
                </template>
            </el-table-column>
        </el-table>
    </template>

    <!--分页-->
    <template>
        <div class="block" style="text-align: center;padding: 20px;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totals">
            </el-pagination>
        </div>
    </template>

    <!--    增加用户表单-->
    <template>
        <el-dialog
                :data="addform"
                title="增加用户"
                :visible.sync="AddDialogVisible"
                width="30%"
        >
            <el-form ref="addForm" :model="addform" :rules="addRules" label-width="100px" >
                <el-form-item label="登录用户名" prop="username">
                    <el-input v-model="addform.username" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="用户全名" prop="fullName">
                    <el-input v-model="addform.fullName" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="addform.contactPhone" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="所属企业名称" prop="companyName">
                    <el-input v-model="addform.companyName" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="创建时间" prop="createdAt">
                    <el-date-picker
                            v-model="addform.createdAt"
                            type="datetime"
                            placeholder="选择创建时间"
                            style="width: 200px"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="是否启用账户" prop="isActive">
                    <el-switch
                            v-model="addform.isActive"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            :active-value="1"
                            :inactive-value="0"
                    ></el-switch>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="AddOnSubmit()">提交</el-button>
                    <el-button @click="cannel()">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </template>

    <!--    编辑表单-->
    <template>
        <el-dialog
                :data="form"
                title="编辑用户"
                :visible.sync="EditDialogVisible"
                width="30%"
        >
            <el-form ref="editForm" :model="form" :rules="editRules" label-width="100px" >
                <el-form-item label="登录用户名" prop="username">
                    <el-input v-model="form.username" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="用户全名" prop="fullName">
                    <el-input v-model="form.fullName" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="所属企业名称" prop="companyName">
                    <el-input v-model="form.companyName" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="创建时间" prop="createdAt">
                    <el-date-picker
                            v-model="form.createdAt"
                            type="datetime"
                            placeholder="选择创建时间"
                            style="width: 200px"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="是否启用账户" prop="isActive">
                    <el-switch
                            v-model="form.isActive"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            :active-value="1"
                            :inactive-value="0"
                    ></el-switch>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="EditOnSubmit()">提交</el-button>
                    <el-button @click="cannel()">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </template>



</div>
</body>
<script src="js/vue.js"></script>
<script src="js/element-ui/lib/index.js"></script>
<link rel="stylesheet" href="js/element-ui/lib/theme-chalk/index.css">
<script src="js/axios-0.18.0.js"></script>

<script>
    var vv = new Vue({
        el: "#app",
        data(){
            return{
                AddDialogVisible:false,
                EditDialogVisible:false,
                delFlag: false,
                currentPage: 1,
                pageSize:5,
                totals:0,
                editingIndex: null,
                addform:{
                    username: "",
                    fullName: "",
                    contactPhone: "",
                    companyName: "",
                    createdAt: "",
                    isActive: 1,
                },

                form: {
                    userId:"",
                    username: "",
                    fullName: "",
                    contactPhone: "",
                    companyName: "",
                    createdAt: "",
                    isActive: "",
                },
                // 添加表单验证规则
                addRules: {
                    fullName: [
                        { required: true, message: '请输入用户全名', trigger: 'blur' }
                    ],
                    username: [
                        { validator: this.validateUsername, trigger: 'blur',required: true }
                    ],
                    companyName: [
                        { required: true, message: '请输入所属企业名称', trigger: 'blur' }
                    ],
                    contactPhone: [
                        { validator: this.validatePhone, trigger: 'blur',required: true }
                    ]
                },
                editRules: {
                    companyName: [
                        { required: true, message: '请输入所属企业名称', trigger: 'blur' }
                    ],
                    username: [
                        { validator: this.validateUsername, trigger: 'blur',required: true}
                    ],
                    fullName: [
                        { required: true, message: '请输入用户全名', trigger: 'blur' }
                    ],
                    contactPhone: [
                        { validator: this.validatePhone, trigger: 'blur',required: true}
                    ]
                },

                searchUser:{
                    username: '',
                    isActive:'',
                    companyName:''
                },
                users: [

                ],
                multipleSelection: []
            }
        },
        methods:{
// 用户名验证（只能包含字母、数字、下划线，长度为4-20个字符）
            validateUsername(rule, value, callback) {
                const reg = /^[a-zA-Z0-9_]{4,20}$/;
                if (!value) {
                    callback(new Error('请输入用户名'));
                } else if (!reg.test(value)) {
                    callback(new Error('用户名只能包含字母、数字、下划线，长度为4-20个字符'));
                } else {
                    callback();
                }
            },
            // 手机号验证
            validatePhone(rule, value, callback) {
                const reg = /^1[3-9]\d{9}$/;
                if (!value) {
                    callback(new Error('请输入联系电话'));
                } else if (!reg.test(value)) {
                    callback(new Error('请输入有效的手机号码'));
                } else {
                    callback();
                }
            },
            adduser(){
                this.AddDialogVisible = true;

            },
            //回显编辑表单
            edit(row){
                this.EditDialogVisible = true;
                this.form = {
                    userId:row.userId,
                    username:row.username,
                    // passwordHash: row.passwordHash,
                    fullName: row.fullName,
                    contactPhone: row.contactPhone,
                    companyName: row.companyName,
                    createdAt: row.createdAt,
                    isActive: Number(row.isActive)

                };
                // this.form = row
                console.log(this.form)
                this.editingIndex = row.userId;

            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize=val
                this.findByPage();

            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage=val
                this.findByPage();
            },
            findByPage(){
                axios({
                    method: "post",
                    url:`/user?currentPage=${this.currentPage}&pageSize=${this.pageSize}`,
                    data:this.searchUser
                }).then((resp)=>{
                    console.log(resp)
                    var page=resp.data.data
                    this.users=page.list
                    this.totals=page.totals
                    for (let i = 0; i < this.users.length; i++) {
                        this.users[i].isActive +='';
                    }

                })
            },
            resetPwd(user) {
                this.$confirm('确认要重置密码吗, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios({
                        method: "put",
                        url: '/user',
                        data:user
                    }).then((resp)=>{
                        if (resp.data){
                            this.$message({
                                type: 'success',
                                message: '重置密码成功!'
                            });
                            this.findByPage()
                        }else {
                            this.$message.error("重置密码失败")
                        }
                    }).catch((error)=>{
                        this.$message.error("编辑失败，错误："+error.message)
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置密码'
                    });
                });
            },
            deluser(userId){
                this.$confirm('确认要删除用户'+userId+'吗, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios({
                        method:"delete",
                        url:`/user/${userId}`
                    }).then((resp)=>{
                        if (resp.data) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.findByPage()
                        }else{
                            this.$message.error("删除失败")
                        }
                    }).catch((error)=>{
                            this.$message.error("删除失败，错误："+error.message)
                        }
                    )
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //修改状态
            changeStatus(user){
                axios({
                    method: "put",
                    url:`/user/status`,
                    data:user
                }).then((resp)=>{
                    if(resp.data) {

                        this.$message(`修改状态成功`);
                    }else{
                        this.$message.error("修改状态失败");
                    }

                })
            },
            //增加用户

            // editmanager(){
            //     EditDialogVisible=true;
            // },
            // 取消编辑
            cannel(){
                this.AddDialogVisible=false;
                this.EditDialogVisible=false;
                this.form={
                    userId: '',
                    username: '',
                    fullName: '',
                    contactPhone: '',
                    companyName: '',
                    createdAt: '',
                    isActive: ''
                };
                this.addform={
                    username: '',
                    fullName: '',
                    contactPhone: '',
                    companyName: '',
                    createdAt: '',
                    isActive: 1
                };

            },
            //提交编辑
            AddOnSubmit() {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        if (!this.addform.createdAt) {
                            this.$message.error('创建时间不能为空');
                            return;
                        }
                        const date = new Date(this.addform.createdAt);
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        const hours = String(date.getHours()).padStart(2, '0');
                        const minutes = String(date.getMinutes()).padStart(2, '0');
                        const seconds = String(date.getSeconds()).padStart(2, '0');
                        this.addform.createdAt = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                        axios({
                            method: "put",
                            url: `/user/add`,
                            data: this.addform
                        }).then((resp) => {
                            if (resp.data.code === 20011) {
                                this.$message(resp.data.msg);
                                this.findByPage()
                                this.AddDialogVisible = false;
                                this.addform = {
                                    username: '',
                                    fullName: '',
                                    contactPhone: '',
                                    companyName: '',
                                    createdAt: '',
                                    isActive: 1
                                }
                            } else {
                                this.$message.error(resp.data.msg);
                            }
                        })
                            .catch((error) => {
                                this.$message.error("增加失败，错误：" + error);
                            });
                    } else {
                        console.log('表单验证失败');
                        return false;
                    }
                });
            },
            // 编辑用户提交
            EditOnSubmit() {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        if (!this.form.createdAt) {
                            this.$message.error('创建时间不能为空');
                            return;
                        }
                        const date = new Date(this.form.createdAt);
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        const hours = String(date.getHours()).padStart(2, '0');
                        const minutes = String(date.getMinutes()).padStart(2, '0');
                        const seconds = String(date.getSeconds()).padStart(2, '0');
                        this.form.createdAt = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                        axios({
                            method: "put",
                            url: `/user/update`,
                            data: this.form
                        }).then((resp) => {
                            if (resp.data.code === 20031) {
                                this.$message("编辑成功");
                                this.findByPage()
                                this.EditDialogVisible = false;
                            } else {
                                this.$message.error(resp.data.msg);
                            }
                        })
                            .catch((error) => {
                                this.$message.error("编辑失败，错误：" + error);
                            });
                    } else {
                        console.log('表单验证失败');
                        return false;
                    }
                });
            }

        },
        mounted(){
            this.findByPage();
        }
    })
</script>
</html>